package com.gitee.apanlh.util.net.http.handler;

import com.gitee.apanlh.exp.HttpConfigException;
import com.gitee.apanlh.exp.HttpException;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.net.http.BaseHttpConfigure;
import com.gitee.apanlh.util.net.http.HttpClient;
import com.gitee.apanlh.util.net.http.HttpRequest;
import com.gitee.apanlh.util.net.http.HttpRequestHeader;
import com.gitee.apanlh.util.net.http.handler.body.cast.HttpRequestBodyCast;
import com.gitee.apanlh.util.valid.ValidParam;

import java.net.HttpURLConnection;

/**
 * 	HTTP配置拦截器，装配实现对HTTP请求头处理
 * 	
 * 	@author Pan
 */
public class HttpHeaderConfigureChain implements HttpRequestInterceptor, BaseHttpConfigure {
	
	@Override
	public HttpRequest chain(HttpRequest httpRequest, HttpClient httpClient, HttpRequestBodyCast bodyCast, HttpInterceptorChain chain) throws HttpException {
		return chain.proceed(configure(httpRequest, httpClient), httpClient);
	}
	
	@Override
	public HttpRequest configure(HttpRequest httpRequest, HttpClient httpClient) throws HttpConfigException {
		HttpRequestHeader header = httpRequest.getHeader();
		HttpURLConnection client = httpClient.getClient();
		
		if (ValidParam.isNotNull(header)) {
			IteratorUtils.entrySet(header.getHeaderMap(), client::setRequestProperty);
		}
		return httpRequest;
	}
}
